#pragma once

#include <iostream>
#include <string>
#include <fstream>
#include <boost/algorithm/string.hpp>
#include <cstring>
#include "cppjieba/Jieba.hpp"

namespace ns_util
{
    class FileUtil
    {
    public:
        static bool ReadFile(const std::string &path, std::string *out)
        {
            std::ifstream in(path, std::ios::in);
            if (!in.is_open())
            {
                std::cerr << "open " << path << " failed!" << std::endl;
                return false;
            }

            std::string line;
            while (getline(in, line))
            {
                *out += line;
            }

            // RAII 可以不显式 close
            // // bug -- 没有关闭文件流 // 错误说法
            in.close();
            return true;
        }

        // .html 文件中的“广告标识”
        // <!-- 广告文件示例：asio_ad.html -->
        // <!-- ad_metadata: bid_price=2.5;budget=100.0 -->

        // 解析广告
        static bool ExtractCommentBlock(const std::string& content, std::string* metadata)
        {
            size_t start = content.find("<!-- ad_metadata: ");
            if (start == std::string::npos)
                return false;
            start += strlen("<!-- ad_metadata: ");

            size_t end = content.find(" -->");
            if (end == std::string::npos)
                return false;
            
            *metadata = content.substr(start, end - start);
            return true;
        }
    };

    // 分词工具
    class StringUtil
    {
    public:
        static void Split(const std::string &target, std::vector<std::string> *out, const std::string &sep)
        {
            boost::split(*out, target, boost::is_any_of(sep), boost::token_compress_on);
            // boost::is_any_of("") 定义一组分割符，任意一个均可触发分割； ",. " -- ',' '.' ' ' 均可触发分割
            // boost::token_compress_on 合并连续的分隔符，避免生成空字符串
        }
    };

    const char *const DICT_PATH = "./dict/jieba.dict.utf8";
    const char *const HMM_PATH = "./dict/hmm_model.utf8";
    const char *const USER_DICT_PATH = "./dict/user.dict.utf8";
    const char *const IDF_PATH = "./dict/idf.utf8";
    const char *const STOP_WORD_PATH = "./dict/stop_words.utf8";

    class JiebaUtil
    {
    private:
        static cppjieba::Jieba jieba;

    public:
        static void CutString(const std::string &s, std::vector<std::string> *words)
        {
            jieba.CutForSearch(s, *words);
        }
    };
    cppjieba::Jieba JiebaUtil::jieba(DICT_PATH, HMM_PATH, USER_DICT_PATH,
                                     IDF_PATH, STOP_WORD_PATH);
}